package com.birdpiss.commons.manager;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.birdpiss.commons.dao.interfaces.AccountDao;
import com.birdpiss.commons.domain.Account;
import com.birdpiss.commons.manager.interfaces.AccountManager;

/**
 * The Class DefaultAccountManager.
 *
 * @author mark
 */
@Service("accountManager")
public class DefaultAccountManager implements AccountManager {

	private static final Logger log = Logger.getLogger(AccountManager.class);
	private AccountDao accountDao;

	/**
	 * Verify DI was setup correctly and perform any post DI initialization.
	 */
	@PostConstruct
	public void initialize() {
		if (this.accountDao == null) throw new BeanCreationException("Must set Account Dao");
	}

	/* (non-Javadoc)
	 * @see com.birdpiss.commons.manager.interfaces.AccountManager#getAccountById(java.lang.Integer)
	 */
	@Override
	public Account getAccountById(Integer accountId) {
		return this.accountDao.getAccountById(accountId);
	}

	/* (non-Javadoc)
	 * @see com.birdpiss.commons.manager.interfaces.AccountManager#getAccountByUserId(java.lang.Integer)
	 */
	@Override
	public Account getAccountByUserId(Integer userId) {
		return this.accountDao.getAccountByUserId(userId);
	}

	/* (non-Javadoc)
	 * @see com.birdpiss.commons.manager.interfaces.AccountManager#insertAccount(com.birdpiss.commons.domain.Account)
	 */
	@Override
	public Account insertAccount(Account account) {
		// We don't insert the same account over and over
		Account existingAccount = this.accountDao.getAccount(account);
		if (existingAccount == null) {
			if (log.isDebugEnabled()) log.debug("Inserting a new account");
			account = this.accountDao.insertAccount(account);
		} else {
			if (log.isDebugEnabled()) log.debug("Returning an existing account");
			account = existingAccount;
		}
		return account;
	}

	/**
	 * Sets the account dao.
	 *
	 * @param accountDao the new account dao
	 */
	@Autowired
	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}

}
